package com.clz.appdesign.appdependence.retrofit_kotlin

import com.clz.appdesign.appdependence.BuildConfig
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

/**
 *  @author chenliangzhi
 *  @date  2018/8/23
 *  @describe
 */
class RetrofitClient private constructor() {
    private var retrofit: Retrofit? = null

    private object Holder {
        val INSTANCE: RetrofitClient = RetrofitClient()
    }

    companion object {
        val instance by lazy { Holder.INSTANCE }
        val CONNECT_TIMEOUT: Long = 60
        val READ_TIMEOUT: Long = 60
        val WRITE_TIMEOUT: Long = 60
        var baseUrl: String = "https://api.youjuke.com/Sales/"
    }

    fun init() {
        val okHttpClient = OkHttpClient().newBuilder()
                .addInterceptor(HttpLoggingInterceptor().setLevel(
                        if (BuildConfig.DEBUG)
                            HttpLoggingInterceptor.Level.BODY
                        else
                            HttpLoggingInterceptor.Level.NONE
                ))
                .retryOnConnectionFailure(true)
                .connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS)
                .readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)
                .writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS)
                .build()
        retrofit = Retrofit.Builder()
                .baseUrl(baseUrl)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .client(okHttpClient)
                .build()

    }

    fun <T> createService(service: Class<T>): T {
        return retrofit!!.create(service)
    }
}